// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Su Hao (suhao@baidu.com)
//
// Description: Object

#include "baidu_ca_object.h"
#include <stdio.h>
#include "baidu_json.h"

using duer::Object;

Object::Object() : _data(baidu_json_CreateObject()), _string(NULL) {
}

Object::~Object() {
    baidu_json_Delete(_data);
    baidu_json_release(_string);
    _string = NULL;
}

void Object::reset() {
    baidu_json_Delete(_data);
    _data = baidu_json_CreateObject();
    baidu_json_release(_string);
    _string = NULL;
}

void Object::putInt(const char* key, int value) {
    baidu_json_AddNumberToObject(_data, key, value);
    baidu_json_release(_string);
    _string = NULL;
}

void Object::putDouble(const char* key, double value) {
    baidu_json_AddNumberToObject(_data, key, value);
    baidu_json_release(_string);
    _string = NULL;
}

void Object::putString(const char* key, const char* value) {
    baidu_json_AddStringToObject(_data, key, value);
    baidu_json_release(_string);
    _string = NULL;
}

void Object::putObject(const char* key, const Object& value) {
    baidu_json_AddItemReferenceToObject(_data, key, value._data);
    baidu_json_release(_string);
    _string = NULL;
}

void Object::putIntArray(const char* key, int value[], size_t length) {
    baidu_json_AddItemToObject(_data, key,
            baidu_json_CreateIntArray(value, length));
    baidu_json_release(_string);
    _string = NULL;
}

void Object::putDoubleArray(const char* key, double value[], size_t length) {
    baidu_json_AddItemToObject(_data, key,
            baidu_json_CreateDoubleArray(value, length));
    baidu_json_release(_string);
    _string = NULL;
}

void Object::putStringArray(const char* key, const char* value[], size_t length) {
    baidu_json_AddItemToObject(_data, key,
            baidu_json_CreateStringArray(value, length));
    baidu_json_release(_string);
    _string = NULL;
}

void Object::putObjectArray(const char* key, Object value[], size_t length) {
    baidu_json* array = baidu_json_CreateArray();

    for (int i = 0; i < length; i ++) {
        baidu_json_AddItemReferenceToArray(array, value[i]._data);
    }

    baidu_json_AddItemToObject(_data, key, array);
    baidu_json_release(_string);
    _string = NULL;
}

void Object::receiveObject(const char* key, baidu_json* object) {
    baidu_json_AddItemToObject(_data, key, object);
}

baidu_json* Object::releaseObject() {
    baidu_json* object = _data;
    _data = baidu_json_CreateObject();
    baidu_json_release(_string);
    _string = NULL;
    return object;
}

const char* Object::toString() {
    if (_string == NULL) {
        _string = baidu_json_PrintUnformatted(_data);
    }

    return _string;
}
